package com.aspsine.multithreaddownload.db;

import com.aspsine.multithreaddownload.util.L;
import ohos.app.Context;
import ohos.data.rdb.RdbOpenCallback;
import ohos.data.rdb.RdbStore;
import ohos.data.rdb.StoreConfig;

import static com.aspsine.multithreaddownload.util.Const.*;
/**
 * Created by aspsine on 15-4-19.
 */
public abstract class AbstractDao<T> {

    private static final String TAG = AbstractDao.class.getName();

    private DBOpenHelper mHelper;

    private RdbStore mRdbStore;

    private static final int DB_VERSION = 1;

    public AbstractDao(Context context) {
        mHelper = new DBOpenHelper(context);
        StoreConfig config = StoreConfig.newDefaultConfig(DB_NAME);
        mRdbStore = mHelper.getRdbStore(config,DB_VERSION,callback,null);
    }

    public RdbStore getWritableDatabase(){
        return mRdbStore;
    }

    private  RdbOpenCallback callback = new RdbOpenCallback() {
        @Override
        public void onCreate(RdbStore rdbStore) {
            //create table
            rdbStore.executeSql("create table if not exists " +
            TABLE_NAME + "(_id integer primary key autoincrement, id integer, " +
             "tag text, uri text, start long, end long, finished long)");
            L.d(TAG,"database create successful !");
        }

        @Override
        public void onUpgrade(RdbStore rdbStore, int i, int i1) {
            L.d(TAG,"database update !"+"before="+i+" after ="+i1);
            mHelper.dropTable(getWritableDatabase());
            mHelper.createTable(getWritableDatabase());
        }
    };

    public RdbStore getReadableDatabase() {
        return getWritableDatabase();// mHelper.getReadableDatabase();
    }

    public void close() {
        getWritableDatabase().close();
    }
}
